<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="WebSocket," />










<meta name="description" content="WebSocketWebSocket简介本文读者将从下面几个方面介绍：  WebSocket是什么？  有什么用？  为什么要用WebSocket?   1. WebSocket是什么？ WebSocket是HTML5下一种新的协议（WebSocket协议本质上是一个基于TCP的协议） 它实现了浏览器与服务器全双工通信，能更好的节省服务器资源和带宽并达到实时通讯的目的 WebSocket是一个持久">
<meta property="og:type" content="article">
<meta property="og:title" content="Websocket前后端通信">
<meta property="og:url" content="https://louchaoyy.gitee.io/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/index.html">
<meta property="og:site_name" content="Chao&#39;s blog">
<meta property="og:description" content="WebSocketWebSocket简介本文读者将从下面几个方面介绍：  WebSocket是什么？  有什么用？  为什么要用WebSocket?   1. WebSocket是什么？ WebSocket是HTML5下一种新的协议（WebSocket协议本质上是一个基于TCP的协议） 它实现了浏览器与服务器全双工通信，能更好的节省服务器资源和带宽并达到实时通讯的目的 WebSocket是一个持久">
<meta property="og:locale">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/1.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/2.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/3.png">
<meta property="article:published_time" content="2022-06-23T13:59:26.000Z">
<meta property="article:modified_time" content="2022-06-24T15:11:22.658Z">
<meta property="article:author" content="Chaoyxy">
<meta property="article:tag" content="WebSocket">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://louchaoyy.gitee.io/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://louchaoyy.gitee.io/blogs/2022/06/23/Websocket前后端通信/"/>





  <title>Websocket前后端通信 | Chao's blog</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chao's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://louchaoyy.gitee.io/blogs/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chao's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Websocket前后端通信</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-06-23T21:59:26+08:00">
                2022-06-23
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2022/06/23/Websocket前后端通信/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="WebSocket"><a href="#WebSocket" class="headerlink" title="WebSocket"></a>WebSocket</h1><h2 id="WebSocket简介"><a href="#WebSocket简介" class="headerlink" title="WebSocket简介"></a>WebSocket简介</h2><p>本文读者将从下面几个方面介绍：</p>
<ul>
<li><p>WebSocket是什么？</p>
</li>
<li><p>有什么用？</p>
</li>
<li><p>为什么要用WebSocket?</p>
</li>
</ul>
<h2 id="1-WebSocket是什么？"><a href="#1-WebSocket是什么？" class="headerlink" title="1. WebSocket是什么？"></a>1. WebSocket是什么？</h2><ul>
<li>WebSocket是HTML5下一种新的协议（WebSocket协议本质上是一个基于TCP的协议）</li>
<li>它实现了浏览器与服务器全双工通信，能更好的节省服务器资源和带宽并达到实时通讯的目的</li>
<li>WebSocket是一个<strong>持久化</strong>的协议</li>
</ul>
<h2 id="2-WebSocket原理"><a href="#2-WebSocket原理" class="headerlink" title="2. WebSocket原理"></a>2. WebSocket原理</h2><ul>
<li>WebSocket约定了一个通信的规范，通过一个握手的机制，客户端和服务器之间能建立一个类似TCP的连接，从而方便它们之间的通信</li>
<li>在WebSocket出现之前，web交互一般是基于http协议的短连接或者长连接</li>
<li>WebSocket是一种全新的协议，不属于http无状态协议，协议名为”ws”</li>
</ul>
<span id="more"></span>

<h2 id="3-WebSocket和HTTP之间的关系"><a href="#3-WebSocket和HTTP之间的关系" class="headerlink" title="3. WebSocket和HTTP之间的关系"></a>3. WebSocket和HTTP之间的关系</h2><img src="/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/1.png" class title="WebSocket和http之间的关系">

<p><strong>相同点：</strong></p>
<ol>
<li><strong>都是基于tcp的，都是可靠性传输协议</strong></li>
<li><strong>都是应用层协议</strong></li>
</ol>
<p><strong>不同点:</strong></p>
<ol>
<li><strong>WebSocket是双向通信协议，模拟Socket协议，可以双向发送或接受信息</strong></li>
<li><strong>HTTP是单向的</strong></li>
<li><strong>WebSocket是需要浏览器和服务器握手进行建立连接的</strong></li>
<li><strong>而http是浏览器发起向服务器的连接，服务器预先并不知道这个连接</strong></li>
</ol>
<p><strong>联系：</strong></p>
<ul>
<li><strong>WebSocket在建立握手时，数据是通过HTTP传输的。但是建立之后，在真正传输时候是不需要HTTP协议的</strong></li>
</ul>
<p><strong>总结（总体过程）：</strong></p>
<p>首先，客户端发起http请求，经过3次握手后，建立起TCP连接；http请求里存放WebSocket支持的版本号等信息，如：Upgrade、Connection、WebSocket-Version等；<br>然后，服务器收到客户端的握手请求后，同样采用HTTP协议回馈数据；<br>最后，客户端收到连接成功的消息后，开始借助于TCP传输信道进行全双工通信。</p>
<h2 id="4-WebSocket解决的问题"><a href="#4-WebSocket解决的问题" class="headerlink" title="4. WebSocket解决的问题"></a>4. WebSocket解决的问题</h2><p><strong>1. http存在的问题</strong></p>
<p>http是一种无状态协议，每当一次会话完成后，服务端都不知道下一次的客户端是谁，需要每次知道对方是谁，才进行相应的响应，因此本身对于实时通讯就是一种极大的障碍<br>http协议采用一次请求，一次响应，每次请求和响应就携带有大量的header头，对于实时通讯来说，解析请求头也是需要一定的时间，因此，效率也更低下<br>最重要的是，需要客户端主动发，服务端被动发，也就是一次请求，一次响应，不能实现主动发送</p>
<p><strong>2. long poll(长轮询)</strong></p>
<p>对于以上情况就出现了http解决的第一个方法——长轮询<br>基于http的特性，简单点说，就是客户端发起长轮询，如果服务端的数据没有发生变更，会 hold 住请求，直到服务端的数据发生变化，或者等待一定时间超时才会返回。返回后，客户端又会立即再次发起下一次长轮询<br>优点是解决了http不能实时更新的弊端，因为这个时间很短，发起请求即处理请求返回响应，实现了“伪·长连接”<br>张三取快递的例子，张三今天一定要取到快递，他就一直站在快递点，等待快递一到，立马取走</p>
<p> <strong>从例子上来看有个问题：</strong></p>
<p>​    假如有好多人一起在快递站等快递，那么这个地方是否足够大，（抽象解释：需要有很高的并发，同时有很多请求等待在这里）</p>
<p>总的来看：</p>
<p>推送延迟。服务端数据发生变更后，长轮询结束，立刻返回响应给客户端。</p>
<p>服务端压力。长轮询的间隔期一般很长，例如 30s、60s，并且服务端 hold 住连接不会消耗太多服务端资源。</p>
<p><strong>3. Ajax轮询</strong></p>
<p>基于http的特性，简单点说，就是规定每隔一段时间就由客户端发起一次请求，查询有没有新消息，如果有，就返回，如果没有等待相同的时间间隔再次询问<br>优点是解决了http不能实时更新的弊端，因为这个时间很短，发起请求即处理请求返回响应，把这个过程放大n倍，本质上还是<code>request = response</code><br><strong>举个形象的例子</strong>（假设张三今天有个快递快到了，但是张三忍耐不住，就每隔十分钟给快递员或者快递站打电话，询问快递到了没，每次快递员就说还没到，等到下午张三的快递到了，but，快递员不知道哪个电话是张三的，（可不是只有张三打电话，还有李四，王五），所以只能等张三打电话，才能通知他，你的快递到了）</p>
<p> <strong>从例子上来看有两个问题：</strong></p>
<p>​    假如说，张三打电话的时间间隔为10分钟，当他收到快递前最后一次打电话，快递员说没到，他刚挂掉电话，快递入库了（就是到了），那么等下一次时间到了，张三打电话知道快递到了，那么这样的通讯算不算实时通讯？很显然，不算，中间有十分钟的时间差，还不算给快递员打电话的等待时间（抽象的解释：每次request的请求时间间隔等同于十分钟，请求解析相当于等待）<br>​    假如说张三所在的小区每天要收很多快递，每个人都采取主动给快递员打电话的方式，那么快递员需要以多快的速度接到，其他人打电话占线也是问题（抽象解释：请求过多，服务端响应也会变慢）</p>
<p>总的来看，Ajax轮询存在的问题：</p>
<ul>
<li><p>推送延迟。</p>
</li>
<li><p>服务端压力。配置一般不会发生变化，频繁的轮询会给服务端造成很大的压力。</p>
</li>
<li><p>推送延迟和服务端压力无法中和。降低轮询的间隔，延迟降低，压力增加；增加轮询的间隔，压力降低，延迟增高</p>
</li>
</ul>
<p><strong>4. WebSocket的改进</strong></p>
<p>一旦WebSocket连接建立后，后续数据都以帧序列的形式传输。在客户端断开WebSocket连接或Server端中断连接前，不需要客户端和服务端重新发起连接请求。在海量并发及客户端与服务器交互负载流量大的情况下，极大的节省了网络带宽资源的消耗，有明显的性能优势，且客户端发送和接受消息是在同一个持久连接上发起，实现了“真·长链接”，实时性优势明显。</p>
<img src="/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/2.png" class title="WebSocket的改进">

<h2 id="5-WebSocket有以下特点："><a href="#5-WebSocket有以下特点：" class="headerlink" title="5. WebSocket有以下特点："></a>5. WebSocket有以下特点：</h2><ul>
<li>是真正的全双工方式，建立连接后客户端与服务器端是完全平等的，可以互相主动请求。而HTTP长连接基于HTTP，是传统的客户端对服务器发起请求的模式。</li>
<li>HTTP长连接中，每次数据交换除了真正的数据部分外，服务器和客户端还要大量交换HTTP header，信息交换效率很低。WebSocket协议通过第一个request建立了TCP连接之后，之后交换的数据都不需要发送 HTTP header就能交换数据，这显然和原有的HTTP协议有区别所以它需要对服务器和客户端都进行升级才能实现</li>
</ul>
<p>本文借鉴了 <a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_54773998/article/details/123863493">https://blog.csdn.net/qq_54773998/article/details/123863493</a> 一文，感谢ohana作者</p>
<h2 id="6-WebSocket的使用"><a href="#6-WebSocket的使用" class="headerlink" title="6. WebSocket的使用"></a>6. WebSocket的使用</h2><p><strong>在服务端，安装 nodejs-websocket</strong></p>
<figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install nodejs<span class="literal">-websocket</span> -<span class="literal">-save</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@name</span>:server</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>:louchao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>:2022/6/22 23:06</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> ws = <span class="built_in">require</span>(<span class="string">&#x27;nodejs-websocket&#x27;</span>)</span><br><span class="line">ws.createServer(<span class="function"><span class="keyword">function</span> (<span class="params">conn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> myTimer = <span class="number">0</span>;</span><br><span class="line">    conn.on(<span class="string">&#x27;text&#x27;</span>, <span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123; <span class="comment">// 收到客户端数据的回调方法</span></span><br><span class="line">        myTimer = <span class="built_in">setInterval</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">            conn.sendText(<span class="string">&quot;我是服务器：&quot;</span>+data) <span class="comment">// 把客服端发送过来的信息再发回去</span></span><br><span class="line">        &#125;,<span class="number">3000</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    conn.on(<span class="string">&#x27;close&#x27;</span>, <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123; <span class="comment">// 关闭服务器的回调方法</span></span><br><span class="line">        <span class="built_in">console</span>.log(e, <span class="string">&#x27;服务端连接关闭&#x27;</span>);</span><br><span class="line">        <span class="comment">// conn.sendText(&quot;我是服务器，我已经关闭了！&quot;)</span></span><br><span class="line">        <span class="built_in">console</span>.log(<span class="keyword">typeof</span> myTimer);</span><br><span class="line">        <span class="built_in">clearInterval</span>(myTimer)</span><br><span class="line">    &#125;)</span><br><span class="line">    conn.on(<span class="string">&#x27;error&#x27;</span>, <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123; <span class="comment">// 服务端连接异常的回调方法</span></span><br><span class="line">        <span class="built_in">console</span>.log(e, <span class="string">&#x27;服务端异常&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    &#125;)</span><br><span class="line">&#125;).listen(<span class="number">8181</span>) <span class="comment">// 监听8181端口，跟客户端连接端口对应</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;服务端已开启&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p><strong>启动服务</strong></p>
<p>在客户端，不需要安装websocket,因为浏览器支持</p>
<p>新建一个文件</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">&quot;sendmsg&quot;</span>&gt;</span>点击发送信息<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">&quot;stop&quot;</span>&gt;</span>停止<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="javascript"></span></span><br><span class="line"><span class="javascript">    <span class="function"><span class="keyword">function</span> <span class="title">contactSocket</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">if</span> (<span class="built_in">window</span>.WebSocket) &#123;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> ws = <span class="keyword">new</span> WebSocket(<span class="string">&#x27;ws://localhost:8181&#x27;</span>)</span></span><br><span class="line"><span class="javascript">            ws.onopen = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(ws);</span></span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(<span class="string">&#x27;连接服务器成功&#x27;</span>);</span></span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(<span class="string">&quot;连接状态：&quot;</span>,ws.readyState);</span></span><br><span class="line"><span class="javascript">                <span class="keyword">let</span> message = &#123;</span></span><br><span class="line"><span class="javascript">                    <span class="attr">id</span>:<span class="number">1001</span>,</span></span><br><span class="line"><span class="javascript">                    <span class="attr">data</span>:<span class="string">&quot;客户端发送过来的数据&quot;</span></span></span><br><span class="line"><span class="javascript">                &#125;</span></span><br><span class="line"><span class="javascript">                ws.send(<span class="built_in">JSON</span>.stringify(message));</span></span><br><span class="line"><span class="javascript"></span></span><br><span class="line"><span class="javascript">                <span class="keyword">let</span> sendMsg = <span class="built_in">document</span>.getElementById(<span class="string">&quot;sendmsg&quot;</span>);</span></span><br><span class="line"><span class="javascript">                sendMsg.addEventListener(<span class="string">&#x27;click&#x27;</span>,<span class="function">()=&gt;</span>&#123;</span></span><br><span class="line"><span class="javascript">                    <span class="built_in">console</span>.log(<span class="string">&quot;我被点击了！！&quot;</span>);</span></span><br><span class="line"><span class="javascript">                    ws.send(<span class="string">&quot;我是点击事件发出的内容！&quot;</span>)</span></span><br><span class="line"><span class="javascript">                &#125;)</span></span><br><span class="line"><span class="javascript">            &#125;</span></span><br><span class="line"><span class="javascript"></span></span><br><span class="line"><span class="javascript">            ws.onmessage = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(e.data)</span></span><br><span class="line"><span class="javascript">            &#125;</span></span><br><span class="line"><span class="javascript">            <span class="comment">// ws.onclose = function () &#123;</span></span></span><br><span class="line"><span class="javascript">            <span class="comment">//     console.log(&#x27;连接已关闭&#x27;);</span></span></span><br><span class="line"><span class="javascript">            <span class="comment">// &#125;</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">let</span> stop = <span class="built_in">document</span>.getElementById(<span class="string">&quot;stop&quot;</span>);</span></span><br><span class="line"><span class="javascript">            stop.addEventListener(<span class="string">&quot;click&quot;</span>,<span class="function">()=&gt;</span>&#123;</span></span><br><span class="line"><span class="javascript">                ws.close();</span></span><br><span class="line"><span class="javascript">            &#125;)</span></span><br><span class="line"><span class="javascript">        &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(<span class="string">&#x27;当前浏览器不支持WebSocket！&#x27;</span>)</span></span><br><span class="line"><span class="javascript">        &#125;</span></span><br><span class="line"><span class="javascript">    &#125;</span></span><br><span class="line"><span class="javascript"></span></span><br><span class="line"><span class="javascript">    contactSocket();</span></span><br><span class="line"><span class="javascript"></span></span><br><span class="line"><span class="javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>笔者在这里，首先新建一个websocket实例，然后连接服务端，给服务端发送一个信息，确定链接之后，服务端每隔一秒会像客户端发送一个消息，如下所示</p>
<img src="/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/3.png" class title="WebSocket在前后端之间的通信">

<p>因此，websocket可以用来实现心跳机制</p>
<p>心跳机制，顾名思义，就是根据心跳检测到此通信依然活跃，还处于连接中</p>
<p>websocketjs更多可以了解<a target="_blank" rel="noopener" href="https://www.npmjs.com/package/nodejs-websocket">https://www.npmjs.com/package/nodejs-websocket</a></p>
<p>在使用websocket的过程中，有时候会遇到客户端网络关闭的情况，而这时候在服务端并没有触发onclose事件。这样会：</p>
<ul>
<li>多余的连接</li>
<li>服务端会继续给客户端发数据，这些数据会丢失</li>
</ul>
<p><strong>所以就需要一种机制来检测客户端和服务端是否处于正常连接的状态。这就是websocket心跳，这个名字非常生动形象，还有心跳说明还活着（保持正常连接），没有心跳说明已经挂掉了（连接断开了）。</strong></p>
<h2 id="7-WebSocket实现心跳机制"><a href="#7-WebSocket实现心跳机制" class="headerlink" title="7. WebSocket实现心跳机制"></a>7. WebSocket实现心跳机制</h2><ol>
<li>连接上之后，每秒发送一个心跳，服务器同样返回一个心跳，用来表示服务器没挂。</li>
<li>断线重连（我们测试的环境是断开网络连接），断开网络后，心跳包无法发送出去，所以如果当前时间距离上次成功心跳的时间超过20秒，说明连接已经出现问题了，此时需要关闭连接。</li>
<li>第一次关闭连接时websocket会尝试重连，设置了一个时间期限，10秒。10秒内如果能连上（恢复网络连接）就可以继续收发消息，连不上就关闭了，并且不会重连。</li>
<li>30秒内收不到服务器消息（心跳每秒发送），我就认为服务器已经挂了，就会调用close事件，然后进入第3步。</li>
</ol>
<p>需要什么</p>
<p>开始考虑得不周到，命名不规范。</p>
<ul>
<li>一个定时器ws.keepAliveTimer，用来每秒发送一次心跳。</li>
<li>上次心跳成功的时间ws.last_health_time以及当前时间let time = new Date().getTime();。</li>
<li>断开连接(ws.close())时的时间reconnect，因为在close事件发生后需要重连10秒。</li>
<li>是否已经重连过reconnectMark。</li>
<li>断开连接(ws.close())时需要保存ws对象tempWs。我曾试图ws = { …ws }发现会丢失绑定的事件。</li>
<li>一个定时时间为30秒的setTimeout定时器ws.receiveMessageTimer，用来表示服务器是否在30秒内返回了消息。</li>
</ul>
<p><strong>代码部分</strong></p>
<p>我是在react中使用websocket心跳的。当用户登录时我会建立websocket连接。由于使用了redux，所以该部分代码放在<code>componentWillReceiveProps</code>中。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">componentWillReceiveProps</span>(<span class="params">nextProps</span>)</span> &#123;</span><br><span class="line">  <span class="keyword">if</span>(nextProps.isLogin &amp;&amp; !<span class="built_in">this</span>.state.notificationSocket) &#123; <span class="comment">// 用户登录了并且没有连接过websocket</span></span><br><span class="line">    <span class="keyword">let</span> ws = <span class="keyword">new</span> WebSocket(<span class="string">`<span class="subst">$&#123;chatUrl&#125;</span>/<span class="subst">$&#123;nextProps.userId&#125;</span>`</span>);</span><br><span class="line">    ws.last_health_time = -<span class="number">1</span>; <span class="comment">// 上一次心跳时间</span></span><br><span class="line">    ws.keepalive = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; </span><br><span class="line">      <span class="keyword">let</span> time = <span class="keyword">new</span> <span class="built_in">Date</span>().getTime();</span><br><span class="line">      <span class="keyword">if</span>(ws.last_health_time !== -<span class="number">1</span> &amp;&amp; time - ws.last_health_time &gt; <span class="number">20000</span>) &#123; <span class="comment">// 不是刚开始连接并且20s</span></span><br><span class="line">        ws.close()</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123; </span><br><span class="line">        <span class="comment">// 如果断网了，ws.send会无法发送消息出去。ws.bufferedAmount不会为0。</span></span><br><span class="line">        <span class="keyword">if</span>(ws.bufferedAmount === <span class="number">0</span> &amp;&amp; ws.readyState === <span class="number">1</span>) &#123; </span><br><span class="line">          ws.send(<span class="string">&#x27;h&amp;b&#x27;</span>);</span><br><span class="line">          ws.last_health_time = time;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(ws) &#123;</span><br><span class="line">      <span class="keyword">let</span> reconnect = <span class="number">0</span>; <span class="comment">//重连的时间</span></span><br><span class="line">      <span class="keyword">let</span> reconnectMark = <span class="literal">false</span>; <span class="comment">//是否重连过</span></span><br><span class="line">      <span class="built_in">this</span>.setState(&#123;</span><br><span class="line">        <span class="attr">notificationSocket</span>: <span class="literal">true</span></span><br><span class="line">      &#125;)</span><br><span class="line">      ws.onopen = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        reconnect = <span class="number">0</span>;</span><br><span class="line">        reconnectMark = <span class="literal">false</span>;</span><br><span class="line">        ws.receiveMessageTimer = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">          ws.close();</span><br><span class="line">        &#125;, <span class="number">30000</span>); <span class="comment">// 30s没收到信息，代表服务器出问题了，关闭连接。如果收到消息了，重置该定时器。</span></span><br><span class="line">        <span class="keyword">if</span>(ws.readyState === <span class="number">1</span>) &#123; <span class="comment">// 为1表示连接处于open状态</span></span><br><span class="line">          ws.keepAliveTimer = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            ws.keepalive();</span><br><span class="line">          &#125;, <span class="number">1000</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">      &#125;</span><br><span class="line">      ws.onerror = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.error(<span class="string">&#x27;onerror&#x27;</span>)</span><br><span class="line">      &#125;</span><br><span class="line">      ws.onmessage = <span class="function">(<span class="params">msg</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">/* 这一注释部分是我的业务逻辑代码，大家可以忽略</span></span><br><span class="line"><span class="comment">        msg = JSON.parse(msg.data);</span></span><br><span class="line"><span class="comment">        let chatObj = JSON.parse(localStorage.getItem(CHATOBJECT)) || &#123;&#125;;</span></span><br><span class="line"><span class="comment">        if(msg &amp;&amp; msg.senderUserId &amp;&amp; !chatObj[msg.senderUserId]) chatObj[msg.senderUserId] = [];</span></span><br><span class="line"><span class="comment">        if(msg.content !== &#x27;h&amp;b&#x27;) &#123;</span></span><br><span class="line"><span class="comment">          if(msg.chat === true) &#123; // 聊天</span></span><br><span class="line"><span class="comment">            // chatObj[msg.senderUserId] = [&lt;p key=&#123;new Date().getTime()&#125;&gt;</span></span><br><span class="line"><span class="comment">            &#123;msg.content&#125;&lt;/p&gt;, ...chatObj[msg.senderUserId]]</span></span><br><span class="line"><span class="comment">            chatObj[msg.senderUserId].unshift(msg.content);</span></span><br><span class="line"><span class="comment">            WindowNotificationUtils.notice(msg.title, msg.content, () =&gt; &#123;</span></span><br><span class="line"><span class="comment">              const &#123; history &#125; = this.props;</span></span><br><span class="line"><span class="comment">              history.replace(&#123;</span></span><br><span class="line"><span class="comment">                pathname: &#x27;/sendNotice&#x27;,</span></span><br><span class="line"><span class="comment">                search: `?senderUserId=$&#123;msg.senderUserId&#125;` // 为什么放在url，因为刷新页面数据不会掉</span></span><br><span class="line"><span class="comment">              &#125;);</span></span><br><span class="line"><span class="comment">            &#125;)</span></span><br><span class="line"><span class="comment">            localStorage.setItem(CHATOBJECT, JSON.stringify(chatObj));</span></span><br><span class="line"><span class="comment">            this.props.dispatch(&#123;</span></span><br><span class="line"><span class="comment">              type: UPDATE_CHAT</span></span><br><span class="line"><span class="comment">            &#125;)</span></span><br><span class="line"><span class="comment">          &#125; else &#123; // 通知</span></span><br><span class="line"><span class="comment">            WindowNotificationUtils.notice(msg.title, msg.content);</span></span><br><span class="line"><span class="comment">          &#125;</span></span><br><span class="line"><span class="comment">        &#125;</span></span><br><span class="line"><span class="comment">      */</span></span><br><span class="line">        <span class="comment">// 收到消息，重置定时器</span></span><br><span class="line">        <span class="built_in">clearTimeout</span>(ws.receiveMessageTimer); </span><br><span class="line">        ws.receiveMessageTimer = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">          ws.close();</span><br><span class="line">        &#125;, <span class="number">30000</span>); <span class="comment">// 30s没收到信息，代表服务器出问题了，关闭连接。</span></span><br><span class="line">      &#125;</span><br><span class="line">      ws.onclose = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">clearTimeout</span>(ws.receiveMessageTimer);</span><br><span class="line">        <span class="built_in">clearInterval</span>(ws.keepAliveTimer);</span><br><span class="line">        <span class="keyword">if</span>(!reconnectMark) &#123; <span class="comment">// 如果没有重连过，进行重连。</span></span><br><span class="line">          reconnect = <span class="keyword">new</span> <span class="built_in">Date</span>().getTime();</span><br><span class="line">          reconnectMark = <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">let</span> tempWs = ws; <span class="comment">// 保存ws对象</span></span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">new</span> <span class="built_in">Date</span>().getTime() - reconnect &gt;= <span class="number">10000</span>) &#123; <span class="comment">// 10秒中重连，连不上就不连了</span></span><br><span class="line">          ws.close();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          ws = <span class="keyword">new</span> WebSocket(<span class="string">`<span class="subst">$&#123;chatUrl&#125;</span>/<span class="subst">$&#123;nextProps.userId&#125;</span>`</span>);</span><br><span class="line">          ws.onopen = tempWs.onopen;</span><br><span class="line">          ws.onmessage = tempWs.onmessage;</span><br><span class="line">          ws.onerror = tempWs.onerror;</span><br><span class="line">          ws.onclose = tempWs.onclose;</span><br><span class="line">          ws.keepalive = tempWs.keepalive;</span><br><span class="line">          ws.last_health_time = -<span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>以上就是websocket心跳的全部实现</strong></p>
<p>原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/real_bird/article/details/77119897">https://blog.csdn.net/real_bird/article/details/77119897</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/alipay.jpg" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/wechatpay.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/WebSocket/" rel="tag"># WebSocket</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/" rel="next" title="NodeJS文件上传与下载">
                <i class="fa fa-chevron-left"></i> NodeJS文件上传与下载
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2022/06/26/axios%E4%BD%BF%E7%94%A8%E5%8F%8A%E5%85%B6%E9%85%8D%E7%BD%AE/" rel="prev" title="axios使用及其配置">
                axios使用及其配置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a target="_blank" rel="noopener" href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blogs/images/cat.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/louchaoyy" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-gitee"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="louchao@louchaoyy.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#WebSocket"><span class="nav-number">1.</span> <span class="nav-text">WebSocket</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#WebSocket%E7%AE%80%E4%BB%8B"><span class="nav-number">1.1.</span> <span class="nav-text">WebSocket简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-WebSocket%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="nav-number">1.2.</span> <span class="nav-text">1. WebSocket是什么？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-WebSocket%E5%8E%9F%E7%90%86"><span class="nav-number">1.3.</span> <span class="nav-text">2. WebSocket原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-WebSocket%E5%92%8CHTTP%E4%B9%8B%E9%97%B4%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="nav-number">1.4.</span> <span class="nav-text">3. WebSocket和HTTP之间的关系</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-WebSocket%E8%A7%A3%E5%86%B3%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-number">1.5.</span> <span class="nav-text">4. WebSocket解决的问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-WebSocket%E6%9C%89%E4%BB%A5%E4%B8%8B%E7%89%B9%E7%82%B9%EF%BC%9A"><span class="nav-number">1.6.</span> <span class="nav-text">5. WebSocket有以下特点：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-WebSocket%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-number">1.7.</span> <span class="nav-text">6. WebSocket的使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-WebSocket%E5%AE%9E%E7%8E%B0%E5%BF%83%E8%B7%B3%E6%9C%BA%E5%88%B6"><span class="nav-number">1.8.</span> <span class="nav-text">7. WebSocket实现心跳机制</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chaoyxy</span>

  
</div>

<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>
-->




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/blogs/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://Chaoyxy.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://louchaoyy.gitee.io/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/';
          this.page.identifier = '2022/06/23/Websocket前后端通信/';
          this.page.title = 'Websocket前后端通信';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://Chaoyxy.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
